//
//  UIImage+Extension.swift
//  MicroBlog
//
//  Created by Apple on 16/9/27.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

extension UIImage {
    //截取当前window的图片
    static func screenShot() -> UIImage {
        let window = UIApplication.shared.keyWindow!
        //开启图形上下文
        UIGraphicsBeginImageContext(window.size)
        //false ->不需要等待更新后才绘制
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
        //从图形上下文中获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭图形上下文
        UIGraphicsEndImageContext()
        return image!
    }
    
    //根据指定宽度等比压缩原图
    func scaleImage(scaleWidth: CGFloat) -> UIImage {
        //压缩后的高度
        let scaleHeight = scaleWidth / self.size.width * self.size.height
        let size = CGSize(width: scaleWidth, height: scaleHeight)
        //开启图片上下文
        UIGraphicsBeginImageContext(size)
        self.draw(in: CGRect(origin: CGPoint.zero, size: size))
        //获取压缩后的图片
        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭
        UIGraphicsEndImageContext()
        return scaleImage!
    }
}
